package com.rraj.common.web.interceptor;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.rraj.common.enums.ResCodeEnums;
import com.rraj.common.exception.BaseRuntimeException;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2017/11/12.
 */
@ControllerAdvice
public class DefaultExceptionHandler implements HandlerExceptionResolver {

    private static Logger LOGGER = LoggerFactory.getLogger(DefaultExceptionHandler.class);
    public static Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]");

    @Override
    @ExceptionHandler(value=Exception.class)
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
        ModelAndView mv = new ModelAndView();
        FastJsonJsonView view = new FastJsonJsonView();
        Map<String, Object> attributes = new HashMap<>();
        if(ex instanceof BaseRuntimeException){
            BaseRuntimeException baseRuntimeException = (BaseRuntimeException)ex;
            attributes.put("resCode", baseRuntimeException.getCode());
            attributes.put("resMsg", baseRuntimeException.getMsg());
        }else if(ex instanceof BindException){
            BindException c = (BindException) ex;
            List<ObjectError> errors = c.getBindingResult().getAllErrors();
            if(CollectionUtil.isNotEmpty(errors)){
                ObjectError objectError = errors.get(0);
                String defaultMessage = objectError.getDefaultMessage();
                attributes.put("resCode", -1);
                if(isContainChinese(defaultMessage)){
                    attributes.put("resMsg", defaultMessage);
                }else {
                    attributes.put("resMsg", ResCodeEnums.SYSTEM_ERROR.getResMsg());
                }
            }
        }else{
            ResCodeEnums resCodeEnums = ResCodeEnums.SYSTEM_ERROR;
            attributes.put("resCode", resCodeEnums.getResCode());
            attributes.put("resMsg", resCodeEnums.getResMsg());
        }
        view.setAttributesMap(attributes);
        mv.setView(view);
        LOGGER.error("系统异常:" + ex.getMessage(), ex);
        return mv;
    }

    public static boolean isContainChinese(String str) {
        if(StrUtil.isNotBlank(str)){
            Matcher m = pattern.matcher(str);
            if (m.find()) {
                return true;
            }
        }
        return false;
    }
}
